Page({
  data: {
    currentIndex: 0,
    playSpeed: 1,
    words: [
      {
        id: 1,
        word: 'apple',
        phonetic: '/ˈæpl/',
        translation: 'n. 苹果',
        example: 'I eat an apple every day.',
        exampleTranslation: '我每天吃一个苹果。'
      },
      {
        id: 2,
        word: 'banana',
        phonetic: '/bəˈnɑːnə/',
        translation: 'n. 香蕉',
        example: 'The monkey is eating a banana.',
        exampleTranslation: '猴子正在吃香蕉。'
      },
      {
        id: 3,
        word: 'orange',
        phonetic: '/ˈɒrɪndʒ/',
        translation: 'n. 橙子',
        example: 'Would you like an orange juice?',
        exampleTranslation: '你想喝橙汁吗？'
      },
      {
        id: 4,
        word: 'grape',
        phonetic: '/ɡreɪp/',
        translation: 'n. 葡萄',
        example: 'These grapes are very sweet.',
        exampleTranslation: '这些葡萄非常甜。'
      },
      {
        id: 5,
        word: 'peach',
        phonetic: '/piːtʃ/',
        translation: 'n. 桃子',
        example: 'The peach is ripe and juicy.',
        exampleTranslation: '这个桃子熟了，很多汁。'
      }
    ]
  },

  // 设置播放速度
  setSpeed(e) {
    const speed = parseFloat(e.currentTarget.dataset.speed);
    this.setData({ playSpeed: speed });
  },

  // 播放单词发音
  playWordAudio() {
    const { currentIndex, words, playSpeed } = this.data;
    const word = words[currentIndex].word;
    // type=0是美音，type=1是英音
    const audioUrl = `https://dict.youdao.com/dictvoice?audio=${word}&type=0`;
    
    const innerAudioContext = wx.createInnerAudioContext();
    innerAudioContext.src = audioUrl;
    innerAudioContext.playbackRate = playSpeed;
    
    innerAudioContext.onError((res) => {
      console.log(res.errMsg);
      wx.showToast({
        title: '音频播放失败',
        icon: 'none'
      });
    });

    innerAudioContext.play();
  },

  // 播放例句发音
  playExampleAudio() {
    const { currentIndex, words, playSpeed } = this.data;
    const example = words[currentIndex].example;
    // 例句使用英音播放
    const audioUrl = `https://dict.youdao.com/dictvoice?audio=${encodeURIComponent(example)}&type=1`;
    
    const innerAudioContext = wx.createInnerAudioContext();
    innerAudioContext.src = audioUrl;
    innerAudioContext.playbackRate = playSpeed;
    
    innerAudioContext.onError((res) => {
      console.log(res.errMsg);
      wx.showToast({
        title: '音频播放失败',
        icon: 'none'
      });
    });

    innerAudioContext.play();
  },

  // 下一个单词
  nextWord() {
    if (this.data.currentIndex < this.data.words.length - 1) {
      this.setData({
        currentIndex: this.data.currentIndex + 1
      });
    } else {
      wx.showToast({
        title: '已完成所有单词学习',
        icon: 'success'
      });
    }
  },

  // 上一个单词
  prevWord() {
    if (this.data.currentIndex > 0) {
      this.setData({
        currentIndex: this.data.currentIndex - 1
      });
    }
  }
}); 